package com.xiongmao.webflux.common.language;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.HttpWebHandlerAdapter;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;

import java.util.Locale;

/**
 * @Author: lao_hu
 * @Date: 2022/2/25 14:21
 * @Description: 使LocaleContextHolder 获取的为当前请求的语言
 */
@Configuration
public class LocaleResolverConfig {
    @Bean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
    public HttpHandler httpHandler(ApplicationContext applicationContext) {
        HttpHandler delegate = WebHttpHandlerBuilder.applicationContext(applicationContext).build();
        return new HttpWebHandlerAdapter(((HttpWebHandlerAdapter) delegate)) {
            @Override
            protected ServerWebExchange createExchange(
                    ServerHttpRequest request, ServerHttpResponse response) {
                ServerWebExchange serverWebExchange = super.createExchange(request, response);
                //从请求头获取当前的语言信息
                final String languageValue = serverWebExchange.getRequest().getHeaders().getFirst("Accept-Language") == null ? "zh" : serverWebExchange.getRequest().getHeaders().getFirst("Accept-Language");
                if (StringUtils.isNoneEmpty(languageValue)) {
                    LocaleContextHolder.setLocaleContext(() ->
                            Locale.forLanguageTag(languageValue));
                } else {
                    LocaleContextHolder.setLocaleContext(serverWebExchange.getLocaleContext());
                }
                return serverWebExchange;
            }
        };
    }
}
